package org.example.springboot.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.example.springboot.common.Result;
import org.example.springboot.entity.Address;
import org.example.springboot.entity.User;
import org.example.springboot.mapper.AddressMapper;
import org.example.springboot.mapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class AddressService {
    private static final Logger LOGGER = LoggerFactory.getLogger(AddressService.class);

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private UserMapper userMapper;

    @Transactional
    public Result<?> createAddress(Address address) {
        try {
            // 如果设置为默认地址，先将该用户的其他地址设为非默认
            if (address.getIsDefault() != null && address.getIsDefault() == 1) {
                resetDefaultAddress(address.getUserId());
            }
            
            // 如果是用户的第一个地址，自动设为默认地址
            LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Address::getUserId, address.getUserId());
            if (addressMapper.selectCount(queryWrapper) == 0) {
                address.setIsDefault(1);
            }
            
            // 如果未设置默认值，则设为非默认
            if (address.getIsDefault() == null) {
                address.setIsDefault(0);
            }
            
            int result = addressMapper.insert(address);
            if (result > 0) {
                LOGGER.info("创建地址成功，地址ID：{}", address.getId());
                return Result.success(address);
            }
            return Result.error("-1", "创建地址失败");
        } catch (Exception e) {
            LOGGER.error("创建地址失败：{}", e.getMessage());
            return Result.error("-1", "创建地址失败：" + e.getMessage());
        }
    }

    @Transactional
    public Result<?> updateAddress(Long id, Address address) {
        address.setId(id);
        try {
            // 如果设置为默认地址，先将该用户的其他地址设为非默认
            if (address.getIsDefault() != null && address.getIsDefault() == 1) {
                resetDefaultAddress(address.getUserId());
            }
            
            int result = addressMapper.updateById(address);
            if (result > 0) {
                LOGGER.info("更新地址成功，地址ID：{}", id);
                return Result.success(address);
            }
            return Result.error("-1", "更新地址失败");
        } catch (Exception e) {
            LOGGER.error("更新地址失败：{}", e.getMessage());
            return Result.error("-1", "更新地址失败：" + e.getMessage());
        }
    }

    public Result<?> deleteAddress(Long id) {
        try {
            // 获取要删除的地址信息
            Address address = addressMapper.selectById(id);
            if (address == null) {
                return Result.error("-1", "地址不存在");
            }
            
            int result = addressMapper.deleteById(id);
            if (result > 0) {
                LOGGER.info("删除地址成功，地址ID：{}", id);
                
                // 如果删除的是默认地址，则将该用户的第一个地址设为默认地址
                if (address.getIsDefault() != null && address.getIsDefault() == 1) {
                    LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(Address::getUserId, address.getUserId());
                    queryWrapper.last("LIMIT 1");
                    Address firstAddress = addressMapper.selectOne(queryWrapper);
                    if (firstAddress != null) {
                        firstAddress.setIsDefault(1);
                        addressMapper.updateById(firstAddress);
                    }
                }
                
                return Result.success();
            }
            return Result.error("-1", "删除地址失败");
        } catch (Exception e) {
            LOGGER.error("删除地址失败：{}", e.getMessage());
            return Result.error("-1", "删除地址失败：" + e.getMessage());
        }
    }

    public Result<?> getAddressById(Long id) {
        Address address = addressMapper.selectById(id);
        if (address != null) {
            // 填充用户信息
            address.setUser(userMapper.selectById(address.getUserId()));
            return Result.success(address);
        }
        return Result.error("-1", "未找到地址");
    }

    public Result<?> getAddressesByUserId(Long userId) {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Address::getUserId, userId);
        // 按默认地址排序，默认地址在前
        queryWrapper.orderByDesc(Address::getIsDefault);
        List<Address> addresses = addressMapper.selectList(queryWrapper);
        if (addresses != null && !addresses.isEmpty()) {
            // 填充用户信息
            addresses.forEach(address -> 
                address.setUser(userMapper.selectById(address.getUserId()))
            );
            return Result.success(addresses);
        }
        return Result.success(addresses);
    }

    public Result<?> getAddressesByPage(Long userId, Integer currentPage, Integer size) {
        LambdaQueryWrapper<Address> queryWrapper = new LambdaQueryWrapper<>();
        if (userId != null) {
            queryWrapper.eq(Address::getUserId, userId);
        }
        // 按默认地址排序，默认地址在前
        queryWrapper.orderByDesc(Address::getIsDefault);

        Page<Address> page = new Page<>(currentPage, size);
        Page<Address> result = addressMapper.selectPage(page, queryWrapper);

        // 填充用户信息
        result.getRecords().forEach(address -> 
            address.setUser(userMapper.selectById(address.getUserId()))
        );

        return Result.success(result);
    }

    public Result<?> deleteBatch(List<Long> ids) {
        try {
            int result = addressMapper.deleteBatchIds(ids);
            if (result > 0) {
                LOGGER.info("批量删除地址成功，删除数量：{}", result);
                return Result.success();
            }
            return Result.error("-1", "批量删除地址失败");
        } catch (Exception e) {
            LOGGER.error("批量删除地址失败：{}", e.getMessage());
            return Result.error("-1", "批量删除地址失败：" + e.getMessage());
        }
    }
    
    /**
     * 设置默认地址
     * @param id 地址ID
     * @return 操作结果
     */
    @Transactional
    public Result<?> setDefault(Long id) {
        try {
            // 获取地址信息
            Address address = addressMapper.selectById(id);
            if (address == null) {
                return Result.error("-1", "地址不存在");
            }
            
            // 先将该用户的所有地址设为非默认
            resetDefaultAddress(address.getUserId());
            
            // 将当前地址设为默认
            address.setIsDefault(1);
            int result = addressMapper.updateById(address);
            
            if (result > 0) {
                LOGGER.info("设置默认地址成功，地址ID：{}", id);
                return Result.success();
            }
            return Result.error("-1", "设置默认地址失败");
        } catch (Exception e) {
            LOGGER.error("设置默认地址失败：{}", e.getMessage());
            return Result.error("-1", "设置默认地址失败：" + e.getMessage());
        }
    }
    
    /**
     * 重置用户的默认地址
     * @param userId 用户ID
     */
    private void resetDefaultAddress(Long userId) {
        LambdaUpdateWrapper<Address> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Address::getUserId, userId);
        updateWrapper.eq(Address::getIsDefault, 1);
        updateWrapper.set(Address::getIsDefault, 0);
        addressMapper.update(null, updateWrapper);
    }
} 